package com.lc.rocketmq.service;

import com.lc.rocketmq.dao.GoodsDao;
import com.lc.rocketmq.po.Goods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liuc
 * @date 2021/8/21
 * @description
 **/
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    //扣减库存
    @Transactional(rollbackFor = Exception.class)
    public boolean reduceStock(Long id, int stock){
        //悲观锁
        Goods goods = goodsDao.forUpadate(id);
        if(goods == null){
            throw new NullPointerException("goods not found");
        }
        if(stock < 0 && goods.getStock() < 1){
            //扣库存需要校验库存信息
            log.warn("stock is zero, goods id : {}",id);
            return false;
        }
        return goodsDao.reduceStock(id,stock,goods.getVersion()) > 0;
        //乐观锁更新+重试
        /*
        int i = 0;
        while(i <= 2){
            if(i != 0){
                goods = goodsDao.findById(id).orElse(null);
            }
            if(goods.getStock() <= 0){
                log.warn("goods {} sell out",id);
                return false;
            }
            int updateNum = goodsDao.reduceStock(id, goods.getVersion());
            if(updateNum > 0){
                return true;
            }
            i++;
        }
        return false;
        */
    }

    @Transactional(rollbackFor = Exception.class)
    public Goods find(Long goodsId) {
        return goodsDao.getOne(goodsId);
    }
}
